package cn.edu.scau.liangshanhero.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

public class FileUtilImpl {
	private static Vector<File> allFilesWithExtends=new Vector<File>();

		// 将每个文件中的字符修改为UTF-8
		public static void replaceStringsInFile(File file, String replaced,
				String replace) {
			// 第一步：读取文件
			// 第二步：修改
			// 第三步：保存// TODO Auto-generated method stub
			Vector<String> resourceVector = new Vector<String>();
			// 先读取文件，替换每一行的内容后将内容添加到content中
			try {
				FileReader reader = new FileReader(file);
				BufferedReader br = new BufferedReader(reader);
				String line;
				while ((line = br.readLine()) != null) {
					System.out.print(line);
					String writer2 = line.replace(replaced, replace);
					resourceVector.add(writer2);
					System.out.println(" ,替换后的行是： " + writer2);
				}
				reader.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			// 将content的内容写到原来的文件中
			try {
				FileWriter writer = new FileWriter(file);
				BufferedWriter bw = new BufferedWriter(writer);
				Iterator<String> resourceVectorIterator = resourceVector.iterator();
				while (resourceVectorIterator.hasNext()) {
					bw.write(resourceVectorIterator.next());
					bw.flush();
					bw.newLine();
				}
				writer.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 获取指定目录下的所有指定类型的文件
		public static Vector<File> getAllFilesWithExtends(File directory,
				Set<String> suffixs) {
			File[] subFile = directory.listFiles();
			System.out.println("现在的目录"+directory);
			for (int i = 0; i < subFile.length; i++) {
				if (subFile[i].isDirectory()) {
					getAllFilesWithExtends(subFile[i].getAbsoluteFile(), suffixs);
				} else {
					String nowFileName = subFile[i].getName();
					String[] fileV = nowFileName.split("\\.");
					String fileSuffix = fileV[fileV.length-1];
					System.out.print(nowFileName+"后缀是："+fileSuffix);
					if (suffixs.contains(fileSuffix) ){//$NON-NLS-1$ //$NON-NLS-2$
						System.out.println("    现在的文件是："+subFile[i].getName());
						allFilesWithExtends.add(subFile[i]);
						System.out.println(""+allFilesWithExtends);
				}
			}
			System.out.println("现在所有的jsp文件是: "+allFilesWithExtends);
			}
			return allFilesWithExtends;
		}

		public static FilenameFilter getFileExtensionFilter(final String extension) {// 指定后綴名过滤
			FilenameFilter filenameFilter = new FilenameFilter() {
				public boolean accept(File file, String fileDirectoryDos) {
					boolean result = fileDirectoryDos.endsWith(extension);
					return result;
				}

			};
			return filenameFilter;
		}

}
